package com.victor.controller.mobile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.Category;
import com.victor.entity.HotTag;
import com.victor.entity.PicturePath;
import com.victor.entity.Series;
import com.victor.entity.Seriesandpicbook;
import com.victor.service.CategoryService;
import com.victor.service.CommentsService;
import com.victor.service.HotTagService;
import com.victor.service.PicturePathService;
import com.victor.service.PicturebookService;
import com.victor.service.SeriesService;
import com.victor.service.SeriesandpicbookService;
import com.victor.service.StatisticsService;
import com.victor.service.YhUsersService;
import com.victor.utils.FileUpload;
import com.victor.utils.Msg;

/**
 * 分类查询controller
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/mobile/picture")
public class PictureController {

	@Autowired
	private PicturebookService service;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private HotTagService tagService;

	@Autowired
	private CommentsService cService;

	@Autowired
	private SeriesService sService;

	@Autowired
	private StatisticsService statisticsService;

	@Autowired
	private SeriesandpicbookService sapService;

	@Autowired
	private YhUsersService userService;

	@Autowired
	private PicturePathService pathService;

	/**
	 * 分类搜索
	 * 
	 * @param pictype
	 * @return
	 */
	@GetMapping("getPictrue/{pictype}/{userid}")
	public Msg getPicByCategory(@PathVariable("pictype") String pictype, @PathVariable("userid") String userid) {
		List<Category> picCategory = categoryService.getPicCategory();
		//Map<String, Object> result = new HashMap<>();
		// for (Category category : picCategory) {
		// int[] categoryids = { category.getCId() };
		// List<Map<String, String>> search = sService.getSearch(null, null,
		// categoryids, pictype, userid);
		// result.put(category.getCId().toString(), search.stream().limit(5l));
		// System.out.println(result);
		// }
		List<Map<String, String>> tempList = sService.getPicByCategory(pictype, userid);
		List<Map<String,Object>> result= new ArrayList<>();
		for (Category category : picCategory) {
			Stream<Map<String, String>> limit = tempList.stream()
					.filter(a -> a.get("scid").equals(String.valueOf(category.getCId()))).limit(5l);
			Map<String, Object> map = new HashMap<>();
			map.put("type", category);
			map.put("value", limit);
			result.add(map);
		}
		return Msg.success().add("list", result);

	}

	/**
	 * 按条件查询
	 * 
	 * @param name
	 * @param ageid
	 * @param categoryid
	 * @return
	 */
	@PostMapping("/getSearch")
	public Msg getSearch(String name, int[] ageIds, int[] categoryIds, String picType, String userid) {
		if (name != null && !name.isEmpty()) {
			HotTag tag = tagService.findByContext(name, picType);
			if (tag == null) {
				boolean bool = tagService.insert(new HotTag(null, name, "0", picType));
				if (!bool) {
					return Msg.fail("新增搜索标签失败");
				}
			} else {
				boolean bool = tagService.addClick(tag.getTId());
				if (!bool) {
					return Msg.fail("增加搜索量失败");
				}
			}
		}
		List<Map<String, String>> result = sService.getSearch(name, ageIds, categoryIds, picType, userid, "1");

		return Msg.success().add("serice", result);
	}

	/**
	 * 获取热门标签
	 * 
	 * @param pictype
	 * @return
	 */
	@GetMapping("/getHotTags/{pictype}")
	public Msg getHotTags(@PathVariable("pictype") String pictype) {
		List<HotTag> tagList = tagService.findByType(pictype);
		return Msg.success().add("tag", tagList);
	}

	/**
	 * 详细介绍页
	 * 
	 * @param sid
	 * @return
	 */
	@GetMapping("/getDetails/{sid}")
	public Msg getDetails(@PathVariable("sid") Integer sid) {
		Map<String, String> details = sService.getDetails(sid);
		if (details == null || details.isEmpty()) {
			return Msg.success().add("details", details).add("comments", null);
		}
		String pid = String.valueOf(details.get("pid"));
		List<Map<String, String>> comments = cService.findByPid(Integer.valueOf(pid));
		return Msg.success().add("details", details).add("comments", comments);
	}

	/**
	 * 绘本系列页
	 * 
	 * @param sid
	 * @param userid
	 * @return
	 */
	@GetMapping("/getSeries/{sid}/{userid}")
	public Msg getSeries(@PathVariable("sid") Integer sid, @PathVariable("userid") String userid) {

		// 1.根据sid 查询系列表信息
		Series series = sService.findById(sid);

		// 2.根据 seriesid 查询出 中间表信息
		List<Seriesandpicbook> findBySid = sapService.findBySid(sid);

		// 3.获取pid 集合
		List<String> pidList = findBySid.stream().map(Seriesandpicbook::getSpPid).collect(Collectors.toList());

		List<Map<String, String>> pictureList = null;
		// 4.获取绘本信息集合
		if (!pidList.isEmpty()) {
			pictureList = service.batchFindByIdsm(pidList, userid);
		}

		return Msg.success().add("series", series).add("picture", pictureList);
	}

	/**
	 * 本周阅读情况
	 * 
	 * @return
	 */
	@GetMapping("/getWeekReport/{pictype}/{userid}")
	public Msg getWeekReport(@PathVariable("userid") String userid, @PathVariable("userid") String pictype) {
		Map<String, Object> map = statisticsService.weekReport(userid, pictype);
		return Msg.success().add("week", map);
	}

	/**
	 * 阅读扫描
	 * 
	 * @param userid
	 * @param pictype
	 * @return
	 */
	@GetMapping("/getReadScan/{pictype}/{userid}")
	public Msg getReadScan(@PathVariable("userid") String userid, @PathVariable("userid") String pictype) {
		Map<String, Object> map = statisticsService.readScann(userid, pictype);
		return Msg.success().add("thisMonth", map.get("thisMonth")).add("lastMonth", map.get("lastMonth"));
	}

	/**
	 * 阅读档案 月份获取
	 * 
	 * @param userid
	 * @param pictype
	 * @return
	 */
	@GetMapping("/getPastMonth/{pictype}/{userid}")
	public Msg getPastMonth(@PathVariable("userid") String userid, @PathVariable("userid") String pictype) {
		List<String> month = statisticsService.findPastMonth(userid, pictype);
		return Msg.success().add("month", month);
	}

	/**
	 * 每月阅读报告
	 * 
	 * @param userid
	 * @param pictype
	 * @param date
	 * @return
	 */
	@GetMapping("/getMonthReport/{pictype}/{userid}/{date}")
	public Msg getMonthReport(@PathVariable("userid") String userid, @PathVariable("pictype") String pictype,
			@PathVariable("date") String date) {
		// 根据userid获取同龄人 id 集合
		List<Integer> sameUseridList = userService.getAgeList(userid);
		// 获取同龄人 每种分类的平均 阅读次数
		List<Map<String, Object>> sameAgeList = statisticsService.batchByUserid(sameUseridList, date, pictype);
		// 获取自己每种分类的平均阅读次数
		sameUseridList.clear();
		sameUseridList.add(Integer.valueOf(userid));
		List<Map<String, Object>> myAgeList = statisticsService.batchByUserid(sameUseridList, date, pictype);
		// 计算每种 分类的百分比
		// 找出有相同分类 和 不同分类的id
		// Map<String, Integer> map = getDifferListByMap(sameAgeList, myAgeList);
		List<Map<String, Object>> result = new ArrayList<>();
		for (Map<String, Object> my : myAgeList) {
			Map<String, Object> temp = new HashMap<>();
			Map<String, Object> rs = new HashMap<>();
			for (Map<String, Object> same : sameAgeList) {
				if (same.get("cid").equals(my.get("cid"))) {
					temp = same;
					break;
				}
			}
			if (temp.isEmpty()) {
				rs.put("cid", my.get("cid"));
				rs.put("cname", my.get("cname"));
				rs.put("percentage", "+" + ((Long) my.get("avg") * 100) + "%");
				rs.put("myread", my.get("avg"));
				rs.put("avgread", 0);
			} else {
				rs.put("cid", my.get("cid"));
				rs.put("cname", my.get("cname"));
				double d = ((Long) my.get("avg") - (Long) temp.get("avg")) / (Long) temp.get("avg") * 100;
				String s = d > 0 ? "+" : "-";
				rs.put("percentage", s + String.format("%.0f", d) + "%");
				rs.put("myread", my.get("avg"));
				rs.put("avgread", temp.get("avg"));
			}
			result.add(rs);
		}

		for (Map<String, Object> same : sameAgeList) {
			Map<String, Object> temp = new HashMap<>();
			Map<String, Object> rs = new HashMap<>();
			for (Map<String, Object> my : myAgeList) {
				if (same.get("cid").equals(my.get("cid"))) {
					temp = my;
					break;
				}
			}
			if (temp.isEmpty()) {
				rs.put("cid", same.get("cid"));
				rs.put("cname", same.get("cname"));
				rs.put("percentage", "-" + ((Long) same.get("avg") * 100) + "%");
				rs.put("myread", 0);
				rs.put("avgread", same.get("avg"));
				result.add(rs);
			}
		}

		return Msg.success().add("result", result);
		// return Msg.success().add("sameAgeList", sameAgeList).add("myAgeList",
		// myAgeList);

		// *****
		// List<Map<String, Object>> result = new ArrayList<>();
		// for (Map<String, Object> my : myAgeList) {
		// for (Map<String, Object> same : sameAgeList) {
		// if (my.get("cid").equals(same.get("cid"))) {
		// Long myavg = (Long) my.get("avg");
		// Long sameavg = (Long) same.get("avg");
		// Long rs = myavg - sameavg;
		// double d = rs / sameavg;
		// Map<String, Object> temp = new HashMap<>();
		// temp.put(String.valueOf((Integer) my.get("cid")), String.format("%.2f", d));
		// result.add(temp);
		// }
		// }
		// }

		// return Msg.success().add("sameAgeList", sameAgeList).add("myAgeList",
		// myAgeList).add("result", result);
	}

	@RequestMapping("/download")
	public void downLoad(HttpServletRequest request, HttpServletResponse response, Integer pid)
			throws ServletException, IOException {
		List<PicturePath> pathList = pathService.findByPid(pid);
		ServletOutputStream outputStream = response.getOutputStream();
		for (PicturePath path : pathList) {
			String image = path.getPImage();
			String video = path.getPAudio();
			if (image != null && !image.isEmpty()) {
				String realname = image.substring(image.lastIndexOf("/") + 1);
				response.setHeader("content-disposition",
						"attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
				FileUpload.download(request, outputStream, image);
			}
			if (video != null && !video.isEmpty()) {
				String realname = video.substring(video.lastIndexOf("/") + 1);
				response.setHeader("content-disposition",
						"attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
				FileUpload.download(request, outputStream, video);
			}
		}
		outputStream.close();
	}

	/**
	 * 获取路径信息
	 * 
	 * @param picid
	 * @return
	 */
	@GetMapping("/getPath/{picid}")
	public Msg getPath(@PathVariable("picid") Integer picid) {
		List<PicturePath> findByPid = pathService.findByPid(picid);
		return Msg.success().add("path", findByPid);
	}

}
